//
//  WorkPlanDetailViewController.m
//  OA
//
//  Created by yy on 17/6/19.
//  Copyright © 2017年 yy. All rights reserved.
//

#import "WorkPlanDetailViewController.h"
#import "AddWorkPlanTableViewCell.h"
#import "WorkHeaderView.h"
#import "ChooseFinishTypeViewController.h"
@interface WorkPlanDetailViewController ()<UITableViewDataSource,UITableViewDelegate,TimeChouseDelegate,UITextFieldDelegate,UITextViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic,strong) UIButton *footerBtn;
@property (nonatomic,assign)NSInteger numOfCell;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *saveBtn;
@property (nonatomic,strong)NSMutableDictionary *dicOfDataSource;//标题时间相关
@property (nonatomic,strong)BasisChooseTimeView *viewOfDate;
@property (nonatomic,strong)NSMutableArray *arrOfDataSource;//cell相关
@property (nonatomic,strong)NSMutableArray *arrOfTypeWithcell;
@property (nonatomic,strong)WorkPlanModel *modelWithToTal;
@end

@implementation WorkPlanDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    if (_isAddWorkPlanType == NO ) {
        self.title = @"工作计划详情";
        
    }else{
        self.title = @"新增工作计划";
    }
    
}

- (void)viewWillAppear:(BOOL)animated{//完成状态返回刷新
    [super viewWillAppear:animated];
    [self initOfDataSouce];
  
}

- (void)initOfDataSouce{
    _numOfCell = 1;
    _arrOfDataSource = [NSMutableArray array];
    _dicOfDataSource = [NSMutableDictionary dictionary];
    [_dicOfDataSource setObject:@"" forKey:@"title"];
    [_dicOfDataSource setObject:@"" forKey:@"beginTime"];
    [_dicOfDataSource setObject:@"" forKey:@"endTime"];
    
    
    if (_isAddWorkPlanType == NO) {
        [self getDataOfId];//详情
        
    }else{
        [self initOfdataOfCell];//新增
        [self initializeUserInterface];
    }
}

- (void)initializeUserInterface{
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    self.tableView.tableHeaderView.frame = CGRectMake(0, 0, Y_mainW, 150);
    self.tableView.tableHeaderView = [self headerView];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    if (_isAddWorkPlanType == NO) {
        self.tableView.tableFooterView = [UIView new];
        self.navigationItem.rightBarButtonItem = nil;
    }else{
        self.tableView.tableFooterView.frame = CGRectMake(0, 0, Y_mainW, 120);
        self.tableView.tableFooterView = [self footerView];
        
        
    }
}

- (void)getDataOfId{
    _arrOfTypeWithcell = [NSMutableArray array];//0是未完成  1:是延期完成 2是按时完成  3是 中止
    
    NSMutableDictionary *param = [NSMutableDictionary dictionaryWithObject:_idOfWorkPlan forKey:@"id"];
//        NSMutableDictionary *param = [NSMutableDictionary dictionaryWithObject:@"00000001" forKey:@"id"];
    [[ToolOfNetWork sharedTools]YrequestURL:oa_getWorkPlanDetail withParams:param finished:^(id responsObject, NSError *error) {
        if (_Success) {
            [MBProgressHUD showSuccess:@"加载成功"];
            _modelWithToTal = [WorkPlanModel objectWithKeyValues:responsObject[@"data"]];
            [self initializeUserInterface];
            NSLog(@"%@",_modelWithToTal.detailList);
            _arrOfDataSource = [NSMutableArray arrayWithArray:_modelWithToTal.detailList];
            for (int i = 0; i <_arrOfDataSource.count; i++) {
                WorkPlanDetailMapModel *detailMapModel = [WorkPlanDetailMapModel objectWithKeyValues:_arrOfDataSource[i]];
                if ([detailMapModel.status isEqualToString:@"0"]) {
                    [_arrOfTypeWithcell addObject:@"0"];//未完成状态
                }else{
                    [_arrOfTypeWithcell addObject:[NSString stringWithFormat:@"%@",detailMapModel.status]]; //非未完成状态
                }
            }
            
            [_tableView reloadData];
        }else{
            [MBProgressHUD showError:@"加载失败"];
        }
    }];
}


//新增
- (void)initOfdataOfCell{
    for (int i = 0; i < _numOfCell-_arrOfDataSource.count; i++) {//_numOfCell + 1;//完成cell数为1时
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:@"" forKey:@"content"];
    [dic setObject:@"" forKey:@"days"];
    [dic setObject:@"" forKey:@"notes"];
//    [dic setObject:@"0" forKey:@"status"];//0：进行中，1：延期完成，2：按时完成，3：中止
    [_arrOfDataSource addObject:dic];
}
}

- (UIView *)headerView{
    NSArray *nib = [[NSBundle mainBundle]loadNibNamed:@"WorkHeaderView" owner:self options:nil];
    UIView *tableHeader = (UIView *)[nib objectAtIndex:0];
    tableHeader.frame = CGRectMake(0, 0, Y_mainW, 160);
    for(UIView *view in tableHeader.subviews)
    {
        if ([view isKindOfClass:[UIView class]])
        {
            
            if (view.tag == TAG_BTN+31) {
                for (UITextView *textView in view.subviews) {
                    if ([textView isKindOfClass:[UITextView class]]) {
                        textView.tag = view.tag;

                        if (_isAddWorkPlanType == YES) {
                            textView.editable = YES;
                            textView.text = [NSString stringWithFormat:@"%@",_dicOfDataSource[@"title"]];
                            textView.delegate = self;
//                            [textView addTarget:self action:@selector(titleTextField:) forControlEvents:UIControlEventEditingChanged];
                        }else{
                            textView.text = _modelWithToTal.name;
                            textView.editable = NO;
                        }
                    }
                }
            }

//            if (view.tag == TAG_BTN+31) {
//                for (UITextField *textField in view.subviews) {
//                    if ([textField isKindOfClass:[UITextField class]]) {
//                        textField.tag = view.tag;
//                        
//                        if (_isAddWorkPlanType == YES) {
//                            textField.enabled = YES;
//                            textField.text = [NSString stringWithFormat:@"%@",_dicOfDataSource[@"title"]];
//                            textField.delegate = self;
//                            [textField addTarget:self action:@selector(titleTextField:) forControlEvents:UIControlEventEditingChanged];
//                        }else{
//                            textField.enabled = NO;
//                            textField.text = _modelWithToTal.name;
//                        }
//                    }
//                }
//            }
            
            if (view.tag == TAG_BTN+32) {
                for (UITextField *textField in view.subviews) {
                    if ([textField isKindOfClass:[UITextField class]]) {
                        textField.tag = view.tag;
                       
                        if (_isAddWorkPlanType == YES) {
                            textField.enabled = YES;
                             textField.text = [NSString stringWithFormat:@"%@",_dicOfDataSource[@"beginTime"]];
                        }else{
                            textField.enabled = NO;
                             textField.text = [_modelWithToTal.begin_date substringToIndex:10];
                        }
                    }
                }
                for (UIButton *btn in view.subviews) {
                    if ([btn isKindOfClass:[UIButton class]]) {
                        if (_isAddWorkPlanType == YES) {
                            btn.hidden = NO;
                            btn.tag = view.tag;
                            [btn addTarget:self action:@selector(headerViewInfoChange:) forControlEvents:UIControlEventTouchUpInside];
                        }else{
                            btn.hidden = YES;
                            
                        }
                        
                    }
                }
            }
            
            if (view.tag == TAG_BTN+33) {
                for (UITextField *textField in view.subviews) {
                    if ([textField isKindOfClass:[UITextField class]]) {
                        textField.tag = view.tag;
                       
                        if (_isAddWorkPlanType == YES) {
                            textField.enabled = YES;
                             textField.text = [NSString stringWithFormat:@"%@",_dicOfDataSource[@"endTime"]];
                        }else{
                            textField.enabled = NO;
                             textField.text = [_modelWithToTal.end_date substringToIndex:10];
                        }
                    }
                }
                
                for (UIButton *btn in view.subviews) {
                    if ([btn isKindOfClass:[UIButton class]]) {
                        if (_isAddWorkPlanType == YES) {
                            btn.hidden = NO;
                            btn.tag = view.tag;
                            [btn addTarget:self action:@selector(headerViewInfoChange:) forControlEvents:UIControlEventTouchUpInside];
                        }else{
                            btn.hidden = YES;
                        }
                       
                    }
                }
            }
        }
    }
    
    return tableHeader;
    
}



#pragma mark —————— headerViewInfoChange
- (void)headerViewInfoChange:(UIButton *)sender{
    [self.view endEditing:YES];

     NSLog(@"btn=%ld",(long)sender.tag);
    [self.view addSubview:self.viewOfDate];
    _viewOfDate.tag = sender.tag;
}

#pragma mark —————— TimeChouseDelegate
-(UIView *)viewOfDate{
    if (!_viewOfDate) {
        NSArray *nib = [[NSBundle mainBundle]loadNibNamed:@"BasisChooseTimeView" owner:self options:nil];
        _viewOfDate = (BasisChooseTimeView *)[nib objectAtIndex:0];
        _viewOfDate.frame = CGRectMake(30, 30, Y_mainW-60, 280);
        _viewOfDate.center = self.view.center;
        _viewOfDate.layer.cornerRadius = 20;
        _viewOfDate.layer.borderWidth = 0.2;
        _viewOfDate.isPrecision = NO;
        _viewOfDate.delegateOfTime = self;
        
    }
    return _viewOfDate;
}
- (NSString *)dateOfDidSelect:(NSString *)str{
    NSLog(@"tag = %ld ～ %@" ,(long)_viewOfDate.tag,str);
    NSInteger  tag = _viewOfDate.tag-TAG_BTN;
    switch (tag) {
        case 32:
            [_dicOfDataSource setObject:str forKey:@"beginTime"];
            break;
        case 33:
            [_dicOfDataSource setObject:str forKey:@"endTime"];
            break;
            
        default:
            break;
    }

    [_viewOfDate removeFromSuperview];
    [_dicOfDataSource setObject:str forKey:@"day"];
    [self.tableView setTableHeaderView:[self headerView]];
    return str;
}
- (void)removeBasisChooseTimeView{
    [_viewOfDate removeFromSuperview];
}

#pragma mark —————— footerView
- (UIView *)footerView{
    UIView *backView = [[UIView alloc]init];
    backView.frame = CGRectMake(0, 0, Y_mainW, 120);
    backView.backgroundColor = BackWiteColor;
    
    _footerBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _footerBtn.backgroundColor = BlueColor;
    _footerBtn.bounds = CGRectMake(0, 0, Y_mainW-60, 50);
     [_footerBtn setTitle:@"添加更多" forState:UIControlStateNormal];
    [_footerBtn addTarget:self action:@selector(addNewPlanAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [backView addSubview:_footerBtn];
    _footerBtn.center = backView.center;
   
    return backView;
}

- (void)addNewPlanAction:(UIButton *)sender{
     NSLog(@"添加更多");
    _numOfCell+=1;
    [self initOfdataOfCell];
    [self.tableView reloadData];
}
#pragma mark —————— 保存
- (IBAction)saveAction:(UIBarButtonItem *)sender {
    [self saveWorkPlan];
}
- (void)saveWorkPlan{
    //oa_saveWorkplan
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setObject:_dicOfDataSource[@"title"] forKey:@"name"];
    [param setObject:_dicOfDataSource[@"title"] forKey:@"content"];
    [param setObject:_dicOfDataSource[@"beginTime"] forKey:@"begin_date"];
    [param setObject:_dicOfDataSource[@"endTime"] forKey:@"end_date"];
    [param setObject:@"0" forKey:@"status"];
    NSString *str = @"";
    
    for (int i = 0; i < _arrOfDataSource.count; i++) {
        NSDictionary *dic  = [NSDictionary dictionaryWithDictionary:_arrOfDataSource[i]];
     str =  [NSString stringWithFormat:@"%@,%@,%@,%@",str,dic[@"content"],dic[@"days"],dic[@"notes"]];
        if (i != _arrOfDataSource.count-1) {
            str =  [NSString stringWithFormat:@"%@;",str];
        }
    }
    [param setObject:str forKey:@"str"];
    
    NSLog(@"%@",param);
 
    [[ToolOfNetWork sharedTools]YrequestURL:oa_saveWorkplan withParams:param  finished:^(id responsObject, NSError *error) {
        if (_Success) {
            _ref();
            [MBProgressHUD showSuccess:@"保存成功"];
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            [MBProgressHUD showError:responsObject[@"message"]];
        }

    }];
}

- (void)refreshAction:(RefreshWorkPlanListVc)refresh{
    _ref = refresh;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark —————— tableView

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (_isAddWorkPlanType) {
        return _numOfCell;
    }else{
        return _arrOfDataSource.count;
    }
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (_isAddWorkPlanType) {
        return 1;
    }else{
        if ([_arrOfTypeWithcell[section] isEqualToString:@"0"]) {
            return 1;
        }else{
            return 2;
        }
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (_isAddWorkPlanType==YES) {//新增工作界面
    
        AddWorkPlanTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AddWorkPlanTableViewCell"];
        if (!cell) {
            cell = [[AddWorkPlanTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"AddWorkPlanTableViewCell"];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        cell.contentTextView.editable = YES;
        cell.dayTextField.enabled = YES;
        cell.noteTextView.editable = YES;
        
        NSInteger tag = TAG_BTN+40;
        cell.contentTextView.tag = tag+1+10*indexPath.section;
        cell.dayTextField.tag = tag+2+10*indexPath.section;
        cell.noteTextView.tag = tag+3+10*indexPath.section;
        
        cell.contentTextView.delegate = self;
        [cell.dayTextField addTarget:self action:@selector(dayTextHaveChanged:) forControlEvents:UIControlEventEditingChanged];
        cell.noteTextView.delegate = self;
        
        cell.contentTextView.text = _arrOfDataSource[indexPath.section][@"content"];
        cell.dayTextField.text = _arrOfDataSource[indexPath.section][@"days"];
        cell.noteTextView.text = _arrOfDataSource[indexPath.section][@"notes"];
   
        return cell;
        
    }else{//工作详情界面
    if (indexPath.row == 1) {//完成cell的条件
//        if (![_arrOfTypeWithcell[indexPath.section] isEqualToString:@"0"]) {//完成cell的条件
        
            EndWorkPlanTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"EndWorkPlanTableViewCell"];
            if (!cell) {
                cell = [[EndWorkPlanTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"EndWorkPlanTableViewCell"];
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
            cell.dic = _arrOfDataSource[indexPath.section];
            cell.endWorkTextView.editable = NO;
            return cell;
            
        }else{//非完成cell的条件
            
            AddWorkPlanTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AddWorkPlanTableViewCell"];
            if (!cell) {
                cell = [[AddWorkPlanTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"AddWorkPlanTableViewCell"];
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            cell.dic = _arrOfDataSource[indexPath.section];
            
            cell.contentTextView.editable = NO;
            cell.dayTextField.enabled = NO;
            cell.noteTextView.editable = NO;
            cell.typeBtn.hidden = NO;

            switch ([ _arrOfDataSource[indexPath.section][@"status"] intValue]) {//状态整型
                
                case 0:
                    [cell.typeBtn setTitle:@"未完成" forState:UIControlStateNormal];
                    [cell.typeBtn addTarget:self action:@selector(notFinishBtnAction:) forControlEvents:UIControlEventTouchUpInside];
                    //未完成icon
                    [cell.typeBtn setImage:Y_IMAGE(@"未完成icon") forState:UIControlStateNormal];
                    [cell.typeBtn setTitleColor:BlueColor forState:UIControlStateNormal];
                    cell.typeBtn.tag = TAG_BTN_B+indexPath.section;
                    break;
                    
                default:
                    cell.typeBtn.userInteractionEnabled = NO;
                    break;
            }

            return cell;
        }
    }
}
//未完成跳转
- (void)notFinishBtnAction:(UIButton *)sender{
    
    ChooseFinishTypeViewController *chooseFinishTypeViewController = VCInSB(@"ChooseFinishTypeViewController", @"ThirdViewControllers");
    chooseFinishTypeViewController.idStr = _modelWithToTal.detailList[sender.tag-TAG_BTN_B][@"id"];
   chooseFinishTypeViewController.workplanId = _idOfWorkPlan;
    [self.navigationController pushViewController:chooseFinishTypeViewController animated:YES];
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (_isAddWorkPlanType) {
        return 320;
    }else{
        if (indexPath.row == 1) {//完成cell的条件
            return 135;
        }else{
            return 320;
        }
    }
    
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark —————— 标题
//- (void)textViewDidChange:(UITextView *)textView{
//    if (textView.tag == TAG_BTN+31) {
//        [_dicOfDataSource setObject:textView.text forKey:@"title"];
//    }
//}

//#pragma mark —————— titleTextField
//- (void)titleTextField:(UITextField *)textField{
//    if (textField.tag == TAG_BTN+31) {
//         [_dicOfDataSource setObject:textField.text forKey:@"title"];
//    }
//
//}
#pragma mark —————— cell.tag info
- (void)textViewDidChange:(UITextView *)textView{
    NSLog(@"textViewDidChange");
    if (textView.tag == TAG_BTN+31) {
        [_dicOfDataSource setObject:textView.text forKey:@"title"];
    }else{
        if (textView.tag%10 == 3) {
            NSInteger row = (textView.tag-40-TAG_BTN-3)/10;
            [ _arrOfDataSource[row] setObject:textView.text  forKey:@"notes"];
        }else{
            NSInteger row = (textView.tag-40-TAG_BTN-1)/10;
            [ _arrOfDataSource[row] setObject:textView.text  forKey:@"content"];
            NSLog(@"_arrOfDataSource==%@",_arrOfDataSource);
        }
    }
    
    
}
- (void)dayTextHaveChanged:(UITextField *)textField{
    NSInteger row = (textField.tag-40-TAG_BTN-2)/10;
    [ _arrOfDataSource[row] setObject:textField.text  forKey:@"days"];
     NSLog(@"_arrOfDataSource==%@",_arrOfDataSource);
}

#pragma mark —————— touchesBegan
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [_viewOfDate removeFromSuperview];
}

@end
